package cn.elead.chaos.sso.server.config;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

import cn.elead.chaos.framework.monitor.console.log.ConsoleLog;
import cn.elead.chaos.framework.monitor.console.log.ConsoleLogQueue;
import lombok.extern.slf4j.Slf4j;

/**
 * 配置WebSocket消息代理端点，即stomp服务端
 *
 * @author luopeng
 * @link https://cloud.tencent.com/developer/article/1096792
 */
@Slf4j
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketAutoConfiguration implements WebSocketMessageBrokerConfigurer {

	@Autowired
	private SimpMessagingTemplate messagingTemplate;

	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		 registry.addEndpoint("/websocket").setAllowedOrigins("*").withSockJS();
	}

	/**
	 * 推送日志到/topic/pullLogger
	 */
	@PostConstruct
	public void pushLogger() {
		ExecutorService executorService = Executors.newFixedThreadPool(2);
		Runnable runnable = () -> {
			while (true) {
				try {
					ConsoleLog log = ConsoleLogQueue.getInstance().poll();
					if (log != null && messagingTemplate != null) {
						messagingTemplate.convertAndSend("/topic/consolelog", log);
					}
				} catch (Exception e) {
					log.warn("推送日志失败:{}", e.getMessage());
				}
			}
		};
		executorService.submit(runnable);
	}
}